package top.jfunc.http.interceptor;

import top.jfunc.common.utils.MapUtil;
import top.jfunc.common.utils.StrUtil;
import top.jfunc.http.request.HttpRequest;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class AddStaticHttpHeaderInterceptor implements Interceptor {
	Map<String,String> headers;

	/**
	 * 以下两个构造方法适合事先就确定几个header的情况
	 */
	public AddStaticHttpHeaderInterceptor(String headerName, String headerValue) {
		this(Collections.singletonMap(headerName, headerValue));
	}
	public AddStaticHttpHeaderInterceptor(Map<String,String> headers) {
		this.headers = headers;
	}

	/**
	 * 配合{@link this#addHeader(String, String)} 或者 {@link this#setHeaders(Map)}使用，方便不确定好多个header的情况
	 */
	public AddStaticHttpHeaderInterceptor() {
	}

	@Override
	public HttpRequest onBefore(HttpRequest httpRequest) throws IOException {
		if(MapUtil.isEmpty(this.headers)){
			return httpRequest;
		}

		this.headers.forEach((headerName,headerValue)->{
			if (StrUtil.isNotEmpty(headerName) && StrUtil.isNotEmpty(headerValue)) {
				httpRequest.addHeader(headerName, headerValue);
			}
		});

		return httpRequest;
	}

	public AddStaticHttpHeaderInterceptor setHeaders(Map<String, String> headers) {
		this.headers = headers;
		return this;
	}

	/**
	 * 配合无参构造函数使用
	 */
	public AddStaticHttpHeaderInterceptor addHeader(String headerName, String headerValue){
		if(null == this.headers){
			this.headers = new HashMap<>();
		}
		this.headers.put(headerName, headerValue);
		return this;
	}
}